<template>
  <div class="app-container">
    <!-- 角色检查加载动画 -->
    <div v-if="roleCheckLoading" class="role-check-loading">
      <el-icon class="is-loading" :size="50" color="#409eff">
        <Loading />
      </el-icon>
      <p class="loading-text">正在加载...</p>
    </div>
    
    <!-- 护理员无权限提示 -->
    <div v-else-if="currentUserRole === '护理员'" class="no-permission-container">
      <div class="no-permission-content">
        <div class="permission-icon">
          <el-icon size="80" color="#f56c6c">
            <Lock />
          </el-icon>
        </div>
        <h2 class="permission-title">您无权限查看</h2>
        <p class="permission-desc">抱歉，您当前的权限不足以访问此页面</p>
        <el-button type="primary" @click="goBack" style="width: 100px;">返回</el-button>
      </div>
    </div>
    
    <!-- 正常内容 -->
    <div v-else>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="bussniessId">
        <el-input v-model="queryParams.bussniessId" placeholder="请输入单据编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="审批人" prop="approverName">
        <el-input v-model="queryParams.approverName" placeholder="请输入审批人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <!-- 新增单据类别下拉框 -->
      <el-form-item label="单据类别" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择单据类别" clearable @change="handleQuery"
          style="width: 180px">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
             <!-- 新增流程状态标签 -->
       <el-form-item prop="handleType">
         <div class="status-tags-container">
           <div class="status-tags">
             <el-tag
               v-for="item in statusOptions"
               :key="item.value"
               :class="['status-tag', queryParams.handleType === item.value ? 'is-dark' : 'is-plain']"
               @click="handleStatusClick(item.value)"
             >
               {{ item.label }}
             </el-tag>
           </div>
         </div>
       </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格内容保持不变 -->
    <el-table v-loading="loading" :data="accraditationrecordList" @selection-change="handleSelectionChange">
      <!-- 表格列定义保持不变 -->
      <el-table-column label="序号" align="center" width="100">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="单据编号" align="center" prop="bussniessId" />
      <el-table-column label="审核步骤" align="center" prop="stepNo" />
      <el-table-column label="单据标题" align="center" prop="currentStep" />
      <el-table-column label="单据类别" align="center" prop="type" />
      <el-table-column label="审批人" align="center" prop="approverName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="finishTime" width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.finishTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程状态" align="center" prop="handleType">
        <template #default="scope">
          <span :class="{
            'status-done': scope.row.handleType == '已审批',
            'status-applying': scope.row.handleType == '申请中',
            'status-closed': scope.row.handleType == '已拒绝',
          }">
            {{ scope.row.handleType }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" v-hasPermi="['accraditationrecord:accraditationrecord:edit']"
            @click="handleCheck(scope.row)">
            {{ scope.row.handleType === '已拒绝' ? '查看' : '处理' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>
  </div>
</template>

<script setup name="Accraditationrecord">
import {
  listAccraditationrecord,
  getAccraditationrecord,
} from "@/api/accraditationrecord/accraditationrecord";
import { getCurrentInstance } from "vue";
import { ref, reactive, toRefs, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Lock, Loading } from "@element-plus/icons-vue";
import { getUser } from "@/api/system/user";
import useUserStore from "@/store/modules/user";

const userStore = useUserStore();

const router = useRouter();
const elderlyId = ref(null);
const stepNo = ref(null);
const { proxy } = getCurrentInstance();

// 当前用户角色
const currentUserRole = ref('');



// 定义单据类别选项
const typeOptions = ref([
  // 根据实际业务场景修改选项值
  { label: "请假", value: "请假" },
  { label: "入住", value: "入住" },
  { label: "退住", value: "退住" },
]);

// 审核状态选项（根据表格中注释的状态定义）
const statusOptions = ref([
  { label: "已审批", value: "已审批" },
  { label: "申请中", value: "申请中" },
  { label: "已拒绝", value: "已拒绝" },
]);

// 统一的查看处理函数，根据单据类别调用不同函数
function handleCheck(row) {
  const type = row.type; // 获取当前行的单据类别
  const status=row.handleType;
  if (type === "请假" && status === "已审批") {
    // 验证参数是否存在（避免空值导致跳转异常）
    if (!row.leaveContentId) {
      ElMessage.warning("缺少请假记录ID，无法查看详情");
      return;
    }
    // 跳转至leaveview.vue，携带leaveId参数（与leaveview页面接收参数一致）
    router.push({
      path: "/views/leave/leavemanage/leaveview", // 目标页面路径（需确认是否与实际路径一致）
      query: { 
        leaveId: row.leaveContentId, // 传递请假记录ID（与leaveview页面的route.query.leaveId对应）
        businessId: row.bussniessId // 可选：传递单据编号，便于详情页展示
      }
    });
    return; // 跳出函数，避免执行后续其他逻辑
  }

  switch (type) {
    case "入住":
      checkCheckIn(row); // 调用入住查看函数
      break;
    case "请假":
      checkLeave(row); // 调用请假查看函数
      break;
    case "退住":
      checkCheckOut(row); // 调用退住查看函数
      break;
    default:
      ElMessage.warning(`未支持的单据类别：${type}`);
  }

}

// 1. 入住单据查看函数（增加流程状态判断）
function checkCheckIn(row) {
  elderlyId.value = row.checkContentId;
  console.log("入住单据 - 传递的elderlyId:", elderlyId.value);
  console.log("当前流程状态:", row.handleType); // 打印状态，便于调试

  // 先判断流程状态是否为“已拒绝”
  if (row.handleType === "已拒绝") {
    // 状态为已拒绝时，跳转到拒绝详情页面
    router.push({
      path: "/togetherwork/togetherwork1/checkreject",
      query: {
        stepNum: row.stepNo, // 参数名与props的stepNum一致
        elderlyId: elderlyId.value, // 参数名与props的elderlyId一致
        opinion: row.opinion, // 传递审批意见
        approveStatus: row.auditStatus, // 传递审批状态
      }
    });
  } else {
    // 其他状态（如申请中、已审批等），保持原有跳转逻辑
    router.push({
      path: "/togetherwork/togetherwork1/checkappeoval",
      query: {
        elderlyId: elderlyId.value,
        stepNo: row.stepNo
      }
    });
  }
}


function checkLeave(row) {
  // 请假单据的参数传递逻辑（根据实际需求调整路径和参数）
  console.log("请假单据 - 查看详情:", row);
  router.push({
    path: "/togetherwork/togetherwork1/leaveappeoval", // 请假详情页面路径
    query: { leaveId: row.leaveContentId, stepNo: row.stepNo }, // 假设用leaveContentId
  });
}


// 3. 退住单据查看函数（新增）
function checkCheckOut(row) {
  // 退住单据的参数传递逻辑（根据实际需求调整路径和参数）
  console.log("退住单据 - 查看详情:", row.createTime);
  router.push({
    path: "/togetherwork/togetherwork1/dropappeoval",
    query: { id: row.dropContentId, stepNum: row.stepNo },
  });
  console.log("退住id" + row.dropContentId + "流程步骤" + row.stepNo);

}

const accraditationrecordList = ref([]);
const loading = ref(true);
const roleCheckLoading = ref(true); // 添加角色检查加载状态
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 30, // 增大每页数量，避免分页导致的数据截断
    opinion: null,
    type: null,
    finishTime: null,
    approverId: null,
    approverName: null,
    approverNameRole: null,
    nextApproverId: null,
    nextApprover: null,
    nextApproverRole: null,
    bussniessId: null,
    currentStep: null,
    nextStep: null,
    auditStatus: null,
    stepNo: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    handleType: null,
    checkContentId: null,
    dropContentId: null,
    leaveContentId: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 查询审批记录列表 */
function getList() {
  loading.value = true;
  listAccraditationrecord(queryParams.value).then((response) => {
    // 获取原始数据
    let allData = response.rows;
    
    // 根据用户角色和单据类别进行过滤
    let filteredData = filterDataByRoleAndType(allData);
    
    // 使用过滤后的数量和总数
    accraditationrecordList.value = filteredData;
    total.value = filteredData.length; // 使用过滤后的数据长度作为总数
    loading.value = false;
  });
}

/** 根据用户角色和单据类别过滤数据 */
function filterDataByRoleAndType(data) {
  if (!currentUserRole.value) {
    return data; // 如果角色未获取到，返回原始数据
  }
  
  return data.filter(item => {
    // 只对"退住"单据类别进行特殊过滤
    if (item.type === '退住') {
      const stepNo = parseInt(item.stepNo);
      
      if (currentUserRole.value === '超级管理员') {
        // 超级管理员：只显示审核步骤为 3 及其以上的
        return stepNo >= 3;
      } else if (currentUserRole.value === '入退审批员') {
        // 入退审批员：只显示审核步骤为 2 的
        return stepNo === 2;
      }
    }
    
    // 其他单据类别或其他角色，显示所有数据
    return true;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 处理标签点击 */
function handleStatusClick(value) {
  // 如果点击的是已选中的标签，则取消选中
  if (queryParams.value.handleType === value) {
    queryParams.value.handleType = null;
  } else {
    queryParams.value.handleType = value;
  }
  handleQuery();
}

 /** 获取标签类型 */
 function getTagType(value) {
   // 改为黑白灰配色，不使用彩色
   return 'info';
 }

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 返回上一页
function goBack() {
  router.go(-1);
}

onMounted(() => {
  getUser(userStore.id).then((response) => {
    //获取当前用户角色
    currentUserRole.value = response.data.roles[0].roleName;
    console.log('当前用户角色:', currentUserRole.value);
    
    // 角色检查完成，关闭加载动画
    roleCheckLoading.value = false;
    
    // 获取角色后加载列表数据
    getList();
  });
});
</script>
<style scoped>
/* 用 :deep() 替代 ::v-deep，更符合 Vue3 规范 */
:deep(.status-done) {
  background-color: white;
  color: #67c23a;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #67c23a;
  /* 简化 border 写法 */
}

:deep(.status-applying) {
  background-color: white;
  color: #f59f00;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #f59f00;
}

:deep(.status-closed) {
  background-color: white;
  color: #f56c6c;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #f56c6c;
}

/* 角色检查加载动画样式 */
.role-check-loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
  background-color: #ffffff;
}

.loading-text {
  margin-top: 20px;
  color: #606266;
  font-size: 16px;
}

/* 无权限页面样式 */
.no-permission-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
  background-color: #f8f9fa;
}

.no-permission-content {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  width: 100%;
}

.permission-icon {
  margin-bottom: 24px;
}

.permission-title {
  color: #f56c6c;
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 16px 0;
}

.permission-desc {
  color: #666;
  font-size: 16px;
  margin: 0 0 32px 0;
  line-height: 1.5;
}

   /* 状态标签容器 - 统一背景 */
  .status-tags-container {
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    padding: 3px 2px;
    display: inline-block;
  }

  /* 状态标签样式 - 黑白灰配色 */
  .status-tags {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }

  .status-tag {
    cursor: pointer;
    transition: all 0.3s;
    user-select: none;
    color: #606266;
    border-color: #dcdfe6;
    background-color: #ffffff;
    font-size: 12px;
    padding: 8px 20px;
    height: auto;
    line-height: 1.5;
  }

  .status-tag:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
  }

  /* 选中状态 - 深灰色 */
  .status-tag.is-dark {
    color: #ffffff;
    background-color: #409EFF;
    border-color: #e0e0e0;
  }

  /* 未选中状态 - 浅灰色边框 */
  .status-tag.is-plain {
    color: #606266;
    background-color: #ffffff;
    border-color: #dcdfe6;
  }
</style>